package com.weetop.cfw.mine.fragment

import android.content.Intent
import android.view.View
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.IntentUtils
import com.blankj.utilcode.util.SpanUtils
import com.gyf.immersionbar.ImmersionBar
import com.weetop.cfw.R
import com.weetop.cfw.application.CFWApplication
import com.weetop.cfw.base.presenter.imp.MinePresenterImp
import com.weetop.cfw.base.ui.fragment.CommonBaseFragment
import com.weetop.cfw.base.view.MineView
import com.weetop.cfw.bean.*
import com.weetop.cfw.constants.Constants
import com.weetop.cfw.constants.UrlConstants
import com.weetop.cfw.event.UpdateUserInfoEvent
import com.weetop.cfw.mine.activity.*
import com.weetop.cfw.other.RichTextWebViewActivity
import com.weetop.cfw.utils.GlideUtils
import com.weetop.cfw.utils.MMKVUtils
import kotlinx.android.synthetic.main.fragment_mine.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 我的界面
 */
class MineFragment: CommonBaseFragment(),View.OnClickListener,MineView {

    private lateinit var minePresenterImp: MinePresenterImp

    private var appCommonProblemStr = UrlConstants.common_problem_web_url//常见问题富文本
    private var appServiceGuaranteeStr = UrlConstants.service_guarantee_web_url//服务保障富文本
    private var appUserAgreementStr = UrlConstants.user_agreement_web_url//用户协议富文本
    private var appUserPolicyStr = UrlConstants.privacy_policy_web_url

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.linearPersonalInfo,R.id.imageUserHeadImg,R.id.textUserName,R.id.textIntroduce -> ActivityUtils.startActivity(PersonalInformationActivity::class.java)
            R.id.imageSettingLogo -> ActivityUtils.startActivity(SettingActivity::class.java)
            R.id.linearWorkshopBrowseRecord -> ActivityUtils.startActivity(WorkshopBrowseRecordActivity::class.java)
            R.id.linearRentalSaleInfo -> {
                val intent = Intent(context,LeaseSaleInformationActivity::class.java)
                intent.putExtra(LeaseSaleInformationActivity.KEY,0)
                ActivityUtils.startActivity(intent)
            }
            R.id.linearMyPublish -> {
                val intent = Intent(context,LeaseSaleInformationActivity::class.java)
                intent.putExtra(LeaseSaleInformationActivity.KEY,1)
                ActivityUtils.startActivity(intent)
            }
            R.id.linearTransactionCompleted -> {
                val intent = Intent(context,LeaseSaleInformationActivity::class.java)
                intent.putExtra(LeaseSaleInformationActivity.KEY,2)
                ActivityUtils.startActivity(intent)
            }
            R.id.linearCloudCurriculum -> ActivityUtils.startActivity(CloudCurriculumBrowseRecordActivity::class.java)
            R.id.linearAudioFrequency -> ActivityUtils.startActivity(AudioFrequencyBrowseRecordActivity::class.java)
            R.id.linearAllMyCourses -> ActivityUtils.startActivity(MyCoursesActivity::class.java)
            R.id.linearLatestCourseItem1 -> ActivityUtils.startActivity(CourseDetailActivity::class.java)
            R.id.linearLatestCourseItem2 -> ActivityUtils.startActivity(CourseDetailActivity::class.java)
            R.id.linearLatestCourseItem3 -> ActivityUtils.startActivity(CourseDetailActivity::class.java)
            R.id.linearCustomerServiceCenter -> ActivityUtils.startActivity(IntentUtils.getDialIntent(Constants.CUSTOMER_SERVICE_PHONE_NUMBER))
            R.id.linearServiceAssurance -> RichTextWebViewActivity.startRichTextWebViewActivity(activity!!,"服务保障",appServiceGuaranteeStr,true)
            R.id.linearUserAgreement -> RichTextWebViewActivity.startRichTextWebViewActivity(activity!!,"用户协议",appUserAgreementStr,true)
            R.id.linearUserPolicy -> RichTextWebViewActivity.startRichTextWebViewActivity(activity!!,"隐私协议",appUserPolicyStr,true)
            R.id.linearCommonProblem -> RichTextWebViewActivity.startRichTextWebViewActivity(activity!!,"常见问题",appCommonProblemStr,true)
        }
    }

    override fun initView() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveUpdateUserInfoEvent(updateUserInfoEvent:UpdateUserInfoEvent){
        minePresenterImp.getPersonalInfoData(this)
    }

    override fun initData() {
        minePresenterImp = MinePresenterImp()
        minePresenterImp.attachView(this)

        setViewsOnClickListener(this,linearPersonalInfo,imageSettingLogo,linearWorkshopBrowseRecord,linearRentalSaleInfo,linearMyPublish,linearTransactionCompleted,linearCloudCurriculum,linearAudioFrequency,linearAllMyCourses,linearLatestCourseItem1,linearLatestCourseItem2,
            linearLatestCourseItem3,linearCustomerServiceCenter,linearServiceAssurance,linearUserAgreement,linearCommonProblem,textIntroduce,textUserName,imageUserHeadImg,linearUserPolicy)
    }

    override fun getLayoutId() = R.layout.fragment_mine

    override fun lazyLoadData() {
        ImmersionBar.with(this).transparentStatusBar().fitsSystemWindows(false).statusBarDarkFont(false).init()
        if(MMKVUtils.getToken().isNotEmpty()){//如果用户登录了，才进行接口请求
            if(isFirstLoadData) {
                minePresenterImp.getPersonalInfoData(this)
            }
            minePresenterImp.toBeAuditedLeaseSaleInformationList(this)
            minePresenterImp.publishedSaleInformationList(this)
            minePresenterImp.getMyCourseList(this)
        }
        /*minePresenterImp.getCommonProblemData(this)
        minePresenterImp.getServiceGuaranteeData(this)
        minePresenterImp.getUserAgreementData(this)*/
    }

    override fun onResume() {
        super.onResume()
        lazyLoadData()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onReceiveLogInBean(logInBean:LogInBean){
        minePresenterImp.getPersonalInfoData(this)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        minePresenterImp.detachView()
    }

    /**
     * 个人资料获取成功
     */
    override fun personalInfoGetSuccess(personalInfoBean: PersonalInfoBean?) {
        if(personalInfoBean != null){
            isFirstLoadData = false
            textUserName.text = "hi,${personalInfoBean.nickname}"
            GlideUtils.loadHeadImg(imageUserHeadImg,"${UrlConstants.baseUrl}${personalInfoBean.face}",imageUserHeadImg)
            if (personalInfoBean.getuLevel()=="1"){

                tvVipLv.text="高级会员"
                CFWApplication.vipLevel="1"
            }else{
                tvVipLv.text="普通会员"
                CFWApplication.vipLevel="0"
            }
        }

    }

    /**
     * 待审核出租出售信息获取成功
     */
    override fun toBeAuditedLeaseSaleInformationGetSuccess(myLeaseSaleInformationListBean: MyLeaseSaleInformationListBean?) {
        textToBeAuditedLeaseSaleInformationNumber.text = "待审核的${myLeaseSaleInformationListBean?.records}"
    }

    /**
     * 已发布出租出售信息获取成功
     */
    override fun publishedSaleInformationGetSuccess(myLeaseSaleInformationListBean: MyLeaseSaleInformationListBean?) {
        textPublishedSaleInformationNumber.text = "已发布的${myLeaseSaleInformationListBean?.records}"
    }

    /**
     * 常见问题富文本获取成功
     */
    override fun commonProblemDataGetSuccess(singlePageIntroduceBean: SinglePageIntroduceBean?) {
        if(singlePageIntroduceBean != null){
            appCommonProblemStr = singlePageIntroduceBean.content
        }
    }

    /**
     * 服务保障富文本获取成功
     */
    override fun serviceGuaranteeGetSuccess(singlePageIntroduceBean: SinglePageIntroduceBean?) {
        if(singlePageIntroduceBean != null){
            appServiceGuaranteeStr = singlePageIntroduceBean.content
        }
    }

    /**
     * 用户协议富文本获取成功
     */
    override fun userAgreementDataGetSuccess(singlePageIntroduceBean: SinglePageIntroduceBean?) {
        if(singlePageIntroduceBean != null){
            appUserAgreementStr = singlePageIntroduceBean.content
        }
    }

    /**
     * 我的课程列表获取成功
     */
    override fun courseListGetSuccess(myCoursesBean: MyCoursesBean?) {
        if(myCoursesBean != null){
            SpanUtils.with(textMyBuyCourses).append("我购买的课程").append(myCoursesBean.records.toString()).setForegroundColor(ColorUtils.getColor(R.color.c_1381CC)).create()
            val courseList = myCoursesBean.data
            when {
                courseList.size >= 3 -> {
                    textMyCoursesItem1.setUrlImage("${UrlConstants.baseUrl}${courseList[0].imgurl}")
                    textMyCoursesItem2.setUrlImage("${UrlConstants.baseUrl}${courseList[1].imgurl}")
                    textMyCoursesItem3.setUrlImage("${UrlConstants.baseUrl}${courseList[2].imgurl}")
                    textMyCoursesTitle1.text = "${courseList[0].title}"
                    textMyCoursesTitle2.text = "${courseList[1].title}"
                    textMyCoursesTitle3.text = "${courseList[2].title}"
                    tvEmptyInfo.visibility=View.GONE

                    linearLatestCourseItem1.setOnClickListener {
                        CourseDetailActivity.startCourseDetailActivity(context!!,courseList[0].infoid,0)
                    }
                    linearLatestCourseItem2.setOnClickListener {
                        CourseDetailActivity.startCourseDetailActivity(context!!,courseList[1].infoid,0)
                    }
                    linearLatestCourseItem3.setOnClickListener {
                        CourseDetailActivity.startCourseDetailActivity(context!!,courseList[2].infoid,0)
                    }
                }
                courseList.size == 2 -> {
                    textMyCoursesItem1.setUrlImage("${UrlConstants.baseUrl}${courseList[0].imgurl}")
                    textMyCoursesItem2.setUrlImage("${UrlConstants.baseUrl}${courseList[1].imgurl}")
                    textMyCoursesTitle1.text = "${courseList[0].title}"
                    textMyCoursesTitle2.text = "${courseList[1].title}"
                    linearLatestCourseItem3.visibility = View.INVISIBLE
                    tvEmptyInfo.visibility=View.GONE

                    linearLatestCourseItem1.setOnClickListener {
                        CourseDetailActivity.startCourseDetailActivity(context!!,courseList[0].infoid,0)
                    }
                    linearLatestCourseItem2.setOnClickListener {
                        CourseDetailActivity.startCourseDetailActivity(context!!,courseList[1].infoid,0)
                    }
                }
                courseList.size == 1 -> {
                    textMyCoursesItem1.setUrlImage("${UrlConstants.baseUrl}${courseList[0].imgurl}")
                    textMyCoursesTitle1.text = "${courseList[0].title}"
                    linearLatestCourseItem2.visibility = View.INVISIBLE
                    linearLatestCourseItem3.visibility = View.INVISIBLE
                    tvEmptyInfo.visibility=View.GONE

                    linearLatestCourseItem1.setOnClickListener {
                        CourseDetailActivity.startCourseDetailActivity(context!!,courseList[0].infoid,0)
                    }
                }
                courseList.size == 0 -> {
                    tvEmptyInfo.visibility=View.VISIBLE
                    linearLatestCourseItem1.visibility = View.INVISIBLE
                    linearLatestCourseItem2.visibility = View.INVISIBLE
                    linearLatestCourseItem3.visibility = View.INVISIBLE
                }
            }
        }
    }

}